import pandas as pd
import src.TqSdk.CountSignal as cs


def count_signal4single_stock(X):
    import inspect

    # 加载文件并获取模块对象
    functions = inspect.getmembers(cs, inspect.isfunction)
    new_df = pd.DataFrame()
    for name, func in functions:
        new_df[name] = func(X)
    return pd.concat([X, new_df], axis=1).dropna()


def preprocess_sz50():
    import os
    from src.EnvironmentVariables import DATA_PATH, BASE_PATH
    from tqdm import tqdm
    from src.Utils.MyUtil import stock_adjust
    target_stocks = pd.read_csv(os.path.join(DATA_PATH, 'targetStocks.csv'))['id']
    dir_path = "E:/Codes/UndergraduateFinalDesign/all_stock_data/stock data"
    usecols = ["date",
               "open",
               "high",
               "low",
               "close",
               "volume",
               "turnover",
               "change",
               "adjust_price"]
    files_path = [os.path.join(dir_path, f"sh{f}.csv") for f in target_stocks]
    dataset = {}

    for i, stock_id in enumerate(tqdm(target_stocks, "Count:")):
        data = count_signal4single_stock(
            stock_adjust(pd.read_csv(files_path[i],
                                     date_parser='date',
                                     usecols=usecols).sort_values('date')))
        dataset[stock_id] = data
    for key, val in tqdm(dataset.items(), "save:"):
        val.to_csv(os.path.join(BASE_PATH, 'data/preProcessedIndexData/sz50stockSignal', f'sh{key}.csv'), index=False)


if __name__ == '__main__':
    preprocess_sz50()
